Skip to content

13. 对象数据映射

使用 Mapster 以外的拓展说明Furion 框架提供了 Mapster 的拓展 Furion.Extras.ObjectMapper.Mapster,如需使用第三方如 AutoMapper 则无需安装此拓展。

13.1 对象映射

简单来说,就是将一个对象的数据根据特定规则批量映射到另一个对象中,减少手工操作和降低人为出错率。如将 DTO 对象映射到 Entity 实体中,反之亦然。

13.2 先看例子

在过去,我们需要将一个对象的值转换到另一个对象中,我们需要这样做,如:

var entity = repository.Find(1);  

var dto = new Dto();  
dto.Id = entity.Id;  
dto.Name = entity.Name;  
dto.Age = entity.Age;  
dto.Address = entity.Address;  
dto.FullName = entity.FirstName + entity.LastName;  
dto.IdCard = entity.IdCard.Replace("1234", "****");  

上面的例子似乎没有任何问题,但是如果很多地方需要这样的赋值操作、或者相同的赋值操作在多个地方使用,又或者一个类中含有非常多的属性或自定义赋值操作。那么这样的操作效率极低,容易出错,且代码非常臃肿和冗余。

所以,实现自动映射赋值和支持特殊配置的需求就有了。目前 C# 平台有两个优秀的对象映射工具:MapsterAutoMapperFurion 框架中,推荐使用 MapsterMapster 是一款极易使用且超高性能的对象映射框架。

13.3 Mapster 使用

现在,我们可以通过 Mapster 提供的对象映射方法:Adapt 方法改造上面的例子:

安装拓展包在 Furion.Core 层安装 Furion.Extras.ObjectMapper.Mapster 拓展包,无需手动调用,Furion 会自动加载并调用。

13.3.1 快速入门

var entity = repository.Find(1);  
var dto = entity.Adapt<Dto>();  

仅仅一行代码就可以实现 entity -> dto 的转换,如果涉及到赋值的复制操作,如 dto.FullNamedto.IdCard,我们只需要自定义映射规则类即可。

13.3.2 自定义映射规则

using Mapster;  
using System;  

namespace Furion.Application  
{  
    public class Mapper : IRegister  
    {  
        public void Register(TypeAdapterConfig config)  
        {  
            config.ForType<Entity, Dto>()  
                .Map(dest => dest.FullName, src => src.FirstName + src.LastName)  
                .Map(dest => dest.IdCard, src => src.IdCard.Replace("1234", "****"));  
        }  
    }  
}  

小知识该映射文件 Mapper.cs 可以放在任何项目或文件夹中,Furion 会在程序启动的时候自动扫描并注入配置。

13.3.3 依赖注入方式

Mapster 除了提供 Adapt 拓展方法以外,同时还提供依赖注入的方式。

public Person(IMapper mapper)  
{  
    var dto =  _mapper.Map<Dto>(entity);  
}  

13.3.4 和 EFCore 配合

Mapster 还提供了 ProjectToType Linq 拓展方法减少我们手动 Select 操作,如:

正常的操作:

var destinations = context.Sources  
    .Select(p => new Destination {  
        Id = p.Id,  
        Name = p.Name,  
        Surname = p.Surname,  
        ....  
    })  
    .ToList();  

使用 Mapster 之后:

 var destinations = context.Sources  
    .ProjectToType<Destination>()  
    .ToList();  

13.4 全局默认配置

Furion 提供全局默认映射配置选项 TypeAdapterConfig.GlobalSettings.Default,可在 Startup 中配置即可,如:

TypeAdapterConfig.GlobalSettings.Default  
    .PreserveReference(true);  

13.5 Dictionary 的键变小写问题

默认情况下,Mapster 映射后,DictionaryKey 会变成小写,这时可以在 Startup.cs 中配置:

TypeAdapterConfig.GlobalSettings.Default  
    .NameMatchingStrategy(NameMatchingStrategy.Exact);  

或者可以单独配置映射:

public class TestMapper : IRegister  
{  
    public void Register(TypeAdapterConfig config)  
    {  
        config.ForType<TestDemo, TestDemo2>()  
            .AfterMapping(dest =>  
            {  
                dest.Dic = new Dictionary<string, string>(dest.Dic, StringComparer.OrdinalIgnoreCase);  
            });  
    }  
}  

13.6 反馈与建议

与我们交流给 Furion 提 Issue


了解更多想了解更多 Mapster 知识可查阅 Mapster - Wiki 文档。